# 从flask框架中导入Flask类
from flask import Flask, redirect, url_for, render_template, session, request, g
import config
from exts import db
from models import Article
from utils import login_log

app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)

with app.app_context():
    db.create_all()


# 初始化Flask类
# Flask()
# 需要传递一个参数__name__
# 1.方便flask框架去寻找资源
# 2.方便flask插件出现错误时，好去寻找问题所在位置


# 装饰器的作用--做一个url与视图函数的映射
@app.route('/')
def hello_world():
    login_url = url_for('login')
    return redirect(login_url)


@app.route('/login', methods=['GET', 'POST'])
def login():
    print('login')
    if request.method == 'GET':
        return render_template('login.html')
    else:
        username = request.form.get('username')
        password = request.form.get('password')
        if username == 'cbl' and password == '123456':
            g.username = username
            login_log(g)
            return '登录成功'
        else:
            return '用户名或密码错误'
        return 'success'


@app.route('/article/<id>')
def article(id):
    return id


@app.route('/index')
def index():
    # return session.get('username')
    return render_template('index.html')


@app.route('/delete')
def delete():
    print(session.get('username'))
    session.pop('username')
    print(session.get('username'))
    return 'success'


@app.route('/add')
def add():
    # 增
    # db.session.add(Article(title="d", content="d"))
    # db.session.commit()
    # 查
    # result=Article.query.filter(Article.title=='d').first()
    # print(result.title)
    # 改
    # article=Article.query.filter(Article.title=='d').first()
    # article.content='new content'
    # db.session.commit()
    # 删
    # article=Article.query.filter(Article.id=='2').first()
    # db.session.delete(article)
    # db.session.commit()
    # article1=Article(title='aaa')
    # article2=Article(title='bbb')
    #
    # tag1=Tag(name='111')
    # tag2=Tag(name='222')
    #
    # article1.tags.append(tag1)
    # article1.tags.append(tag2)
    #
    # article2.tags.append(tag1)
    # article2.tags.append(tag2)
    # db.session.add(article1)
    # db.session.add(article2)
    # db.session.add(tag1)
    # db.session.add(tag2)
    #
    # db.session.commit()
    return g.username


@app.route('/search/')
def search():
    print(request.args)
    return render_template('search.html')


@app.before_request
def check_token():
    user='ddd'


@app.context_processor
def context():
    return {'username': 'cbl'}
